package org.skydiveapp;

import org.skydiveapplibrary.repository.LocationRepository;
import org.skydiveapplibrary.ui.LocationSelectListAdapter;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class LocationSelectListActivity extends BaseListActivity
{
	// menus
	private MenuItem addMenu;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{ 
		super.onCreate(savedInstanceState);
		
		// init view
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		setHeaderText(R.string.select_location_label);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		loadData();
	}
	
	@Override
	protected void onListItemClick(ListView listView, View view, int indx, long id)
	{
		// get current selection
    	int previousSelectedId = getIntent().getIntExtra(Constants.EXTRA_LOCATION_ID, -1);
    	int newSelectedId = (int)id;
    	
    	// create new intent
    	Intent intent =  new Intent();
    	
    	// if different than previous
    	if (previousSelectedId != newSelectedId)
    		intent.putExtra(Constants.EXTRA_LOCATION_ID, newSelectedId);

    	// set result, finish
		setResult(RESULT_OK, intent);
		finish();

	}
	
	private void loadData()
	{
		// populate
		LocationRepository repository = new LocationRepository(this);
		LocationSelectListAdapter adapter = new LocationSelectListAdapter(
				this,
				repository.getLocations());
		setListAdapter(adapter);
		
		// set initial selection
		int selectedId = getIntent().getIntExtra(Constants.EXTRA_LOCATION_ID, -1);
		for (int index = 0; index < adapter.getCount(); index++)
		{
			getListView().setItemChecked(index,
					adapter.getItems().get(index).getId() == selectedId); 
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		addMenu = menu.add(R.string.add_button);
		addMenu.setIcon(R.drawable.ic_menu_add);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item == addMenu)
		{
        	Intent intent = new Intent(this, LocationEditActivity.class);
        	startActivity(intent);
    		return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
	}
} 